package model

import "time"

// Task db模型
type Task struct {
	ID          string `gorm:"primarykey"`
	TaskName    string `gorm:"size:1000"`
	TaskType    string `gorm:"size:1000"`
	TaskComment string `gorm:"size:1000;default:'default comment'"`
	Cancelable  bool   `gorm:"default:false"`
	Percentage  int64
	Message     string    `gorm:"size:1000"`
	Status      string    `gorm:"size:1000"`
	CreatedAt   time.Time `gorm:"column:created_at"`
	UpdatedAt   time.Time `gorm:"column:updated_at"`
}

type Task_Action int64

//枚举类型
const (
	Start Task_Action = iota + 1
	Stop
)

func (m Task_Action) String() string {
	switch m {
	case Start:
		return "Start"
	case Stop:
		return "Stop"
	}
	return "UNKNOWN"
}

type Task_Status int64

//枚举类型
const (
	Init Task_Status = iota + 1
	Running
	Stopped
	Successed
	Failed
)

// GetTask 用ID获取Task
func GetTask(ID interface{}) (Task, error) {
	var task Task
	result := DB.Where("ID = ?", ID).First(&task)
	return task, result.Error
}

// Get全部task
func GetTaskAll() (tasks []Task) {
	DB.Model(&Task{}).Order("created_at DESC").Find(&tasks)
	return tasks
}

// Get全部task
func GetTaskByPage(page int, pageSize int) (int64, []Task) {
	var tasks []Task
	var totalcount int64
	DB.Model(&Task{}).Count(&totalcount)
	DB.Model(&Task{}).Offset((page - 1) * pageSize).Limit(pageSize).Order("created_at DESC").Find(&tasks)
	return totalcount, tasks
}

func (t *Task) CreateTask() error {
	// 创建task
	err := DB.Create(t).Error
	return err

}

func (t *Task) DeleteTask() error {
	// 删除task
	err := DB.Delete(t).Error
	return err

}
func (t *Task) UpdateTask() error {
	// 更新task
	err := DB.Model(t).Where("ID=?", t.ID).Updates(t).Error
	return err

}
